let cron = require('node-cron');
let mongoose = require('mongoose');

const CensusModel = mongoose.models['Census']
module.exports = {
    init(){
        this.statics = [];
        let self = this;
        cron.schedule('0 0 * * * *', async function(){
            await self.autoSave();
        });
        // setTimeout(this.autoSave,5000)
    },
    onStatics(data){
        // var
        // console.log('保存点击统计onStatics:',data)
        let all = data.split(',');
        for(let i=0; i<all.length-3; i+=4){
            let sceneid = all[i];
            let x = all[i+1];
            let y = all[i+2];
            let count = all[i+3]
            let scene = this.statics.find(item=>{return item.scene == sceneid && item.x==x && item.y==y})
            if(!scene){
                scene = {count:count,scene:sceneid,x:x,y:y}
                this.statics.push(scene)
            }
            scene.count += count;
        }

        // this.autoSave();
    },
    async autoSave(){
        console.log('保存点击统计onStatics:',this.statics.length)
        let statics = this.statics;
        this.statics = []
        let data = new Date()
        // let time = data.getFullYear()+'-'+(data.getMonth()+1)+'-'+data.getDate()+'-'+data.getHours()
        for(let i=0; i<statics.length; i++){
            let stat = statics[i];
            await CensusModel.create({
                type:'hot_'+stat.scene,
                group : parseInt(stat.x) +'_'+stat.y,
                count :stat.count,
                timeTick:data.getTime()
            });
        }
        console.log('保存点击统计 写入完成')
    }
}